/* eslint-disable no-useless-concat */
import React, {PureComponent} from 'react';
import {Table, Card, Row, Col} from 'antd';
import moment from 'moment';
import {formatPercent} from '../utils';
import {addMonths, polylinelist} from './utils';
import DataSet from '@antv/data-set';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {reportSettlementList, compareTypeSelect} from '../Enum';
import PropTypes from 'prop-types';
import {Chart, Geom, Axis, Tooltip, Legend, Label, View} from 'bizcharts';
import {
    TABLE,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT} from '../constants';
const year = moment(new Date()).format('YYYY');

const yearMonth = moment(new Date()).format('YYYY-MM');
export class TableCyclePanel extends PureComponent {
    state = {
        loading: false
    };
    onClickLegend = (ev, legendItems, box) => {
        setTimeout(() => {
            const checked = ev.checked;
            const value = ev.item.value;
            if(value === box)
                if(checked) {
                    this.chart.get('views')[0].get('geoms')[0].show();
                } else {
                    this.chart.get('views')[0].get('geoms')[0].hide();
                }
            const newLegend = legendItems.map(d => {
                if(d.value === value)
                    return Object.assign({}, d, {
                        checked,
                    });
                return d;
            });
            this.chart.filter('type', t => {
                const legendCfg = newLegend.find(i => i.value === t);
                return legendCfg && legendCfg.checked;
            });

            this.chart.legend({
                items: newLegend
            });
            this.chart.repaint();
        }, 0);
    }
    render() {
        const {conditions, data, loading, hasError} = this.props;
        const contents = conditions.compareType === compareTypeSelect.环比 && polylinelist(conditions.linkRatioTime, data, yearMonth);
        const {formatMessage} = this.props.intl;
        const columnsBoth = [
            {
                title: formatMessage({
                    id: 'tablePanel.column.sernum',
                    defaultMessage: '序号'
                }),
                dataIndex: 'sernum',
                render: (t, d, i) => i + 1
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.region',
                    defaultMessage: '区域'
                }),
                dataIndex: 'region'
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode'
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.market',
                    defaultMessage: '市场'
                }),
                dataIndex: 'market'
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.settlementNum',
                    defaultMessage: '结算单号'
                }),
                dataIndex: 'settlementNum'
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.applicationMonth',
                    defaultMessage: '申请月份'
                }),
                dataIndex: 'applicationMonth'
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.reviewCompletionDate',
                    defaultMessage: '审核完成日期'
                }),
                dataIndex: 'reviewCompletionDate'
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.preSettlementTime',
                    defaultMessage: '预结算时间'
                }),
                dataIndex: 'preSettlementTime'
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.settlementTime',
                    defaultMessage: '结算时间'
                }),
                dataIndex: 'settlementTime'
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.PIUploadTime',
                    defaultMessage: 'PI上传日期'
                }),
                dataIndex: 'PIUploadTime'
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.reportToFinanceTime',
                    defaultMessage: '上报财务时间'
                }),
                dataIndex: 'reportToFinanceTime',
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.accountTime',
                    defaultMessage: '挂账日期'
                }),
                dataIndex: 'accountTime'
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.cumulativeSettlementBusiness',
                    defaultMessage: '累计结算周期-业务'
                }),
                dataIndex: 'cumulativeSettlementBusiness'
            }, {
                title: formatMessage({
                    id: 'tableCyclePanel.column.cumulativeSettlementBill',
                    defaultMessage: '累计结算周期-单据'
                }),
                dataIndex: 'cumulativeSettlementBill'
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.settlementAmount',
                    defaultMessage: '结算金额'
                }),
                dataIndex: 'settlementAmount'
            }];
        const columnsCycleYear = [
            {
                title: formatMessage({
                    id: 'tablePanel.column.month',
                    defaultMessage: '月份'
                }),
                dataIndex: 'month',
                render: t => `${t}${formatMessage({
                    id: 'tablePanel.list.month',
                    defaultMessage: '月'
                })}`
            }, {
                title: `${year - 1}${formatMessage({
                    id: 'tablePanel.column.settlementCycle',
                    defaultMessage: '结算周期'
                })}`,
                dataIndex: 'startSettlementCycle'
            }, {
                title: `${year}${formatMessage({
                    id: 'tablePanel.column.settlementCycle',
                    defaultMessage: '结算周期'
                })}`,
                dataIndex: 'endSettlementCycle'
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.changeRate',
                    defaultMessage: '变化率'
                }),
                dataIndex: 'changeRate',
                render: t => formatPercent(t)
            }];
        const columnsCycleLinkRatio = [
            {
                title: formatMessage({
                    id: 'tablePanel.column.sernum',
                    defaultMessage: '序号'
                }),
                dataIndex: 'sernum',
                render: (t, d, i) => i + 1
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.region',
                    defaultMessage: '区域'
                }),
                dataIndex: 'region'
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode'
            }, {
                title: formatMessage({
                    id: 'tablePanel.column.market',
                    defaultMessage: '市场'
                }),
                dataIndex: 'market'
            }, {
                title: addMonths(10, yearMonth),
                dataIndex: 'n1',
            }, {
                title: addMonths(9, yearMonth),
                dataIndex: 'n2',
            }, {
                title: addMonths(8, yearMonth),
                dataIndex: 'n3',
            }];
            // , {
            //     title: addMonths(7, yearMonth),
            //     dataIndex: 'n4'
            // }, {
            //     title: addMonths(6, yearMonth),
            //     dataIndex: 'n5'
            // }, {
            //     title: addMonths(5, yearMonth),
            //     dataIndex: 'n6'
            // }, {
            //     title: addMonths(4, yearMonth),
            //     dataIndex: 'n7'
            // }, {
            //     title: addMonths(3, yearMonth),
            //     dataIndex: 'n8'
            // }, {
            //     title: addMonths(2, yearMonth),
            //     dataIndex: 'n9'
            // }, {
            //     title: addMonths(1, yearMonth),
            //     dataIndex: 'n10'
            // }, {
            //     title: addMonths(0, yearMonth),
            //     dataIndex: 'n11'
            // }, {
            //     title: addMonths(-1, yearMonth),
            //     dataIndex: 'n12'
            // }];

        const locale = {
            emptyText: hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const list = data.map(v => ({
            month: String(v.month),
            [`${year - 1}${formatMessage({
                id: 'tablePanel.column.settlementCycle',
                defaultMessage: '结算周期'
            })}`]: v.startSettlementCycle,
            [`${year}${formatMessage({
                id: 'tablePanel.column.settlementCycle',
                defaultMessage: '结算周期'
            })}`]: v.endSettlementCycle,
            [formatMessage({
                id: 'tablePanel.column.changeRate',
                defaultMessage: '变化率'
            })]: v.changeRate
        }));
        //柱状图与折线图
        const dsRate = new DataSet();
        dsRate.setState('type', '');
        const dvRate = dsRate.createView().source(list);
        dvRate.transform({
            type: 'fold',
            fields: [`${year - 1}${formatMessage({
                id: 'tablePanel.column.settlementCycle',
                defaultMessage: '结算周期'
            })}`, `${year}${formatMessage({
                id: 'tablePanel.column.settlementCycle',
                defaultMessage: '结算周期'
            })}`],
            key: 'type', // key字段
            value: 'value', // value字段
        }).transform({
            type: 'filter',
            callback: d => d.type !== dsRate.state.type
        });
        const scale = {
            [formatMessage({
                id: 'tablePanel.column.changeRate',
                defaultMessage: '变化率'
            })]: {
                type: 'linear',
                formatter: val => formatPercent(val)
            }
        };
        const legendItems = [
            {
                value: `${year - 1}${formatMessage({
                    id: 'tablePanel.column.settlementCycle',
                    defaultMessage: '结算周期'
                })}`,
                marker: {
                    symbol: 'square',
                    fill: '#A4C2E5',
                    radius: 5
                }
            },
            {
                value: `${year}${formatMessage({
                    id: 'tablePanel.column.settlementCycle',
                    defaultMessage: '结算周期'
                })}`,
                marker: {
                    symbol: 'square',
                    fill: '#F5B297',
                    radius: 5
                }
            },
            {
                value: [formatMessage({
                    id: 'tablePanel.column.changeRate',
                    defaultMessage: '变化率'
                })],
                marker: {
                    symbol: 'hyphen',
                    stroke: '#A5A5A5',
                    radius: 5,
                    lineWidth: 3
                }
            }
        ];
        const cols = {
            month: {
                range: [0, 1]
            }
        };
        return (
            <Card>
                { conditions.compareType === compareTypeSelect.不同比不环比 && <Table
                    className="white-space-nowrap"
                    columns={columnsBoth}
                    dataSource={data}
                    rowKey="id"
                    pagination={false}
                    loading={loading || this.state.loading}
                    locale={locale}
                    {...TABLE}/>}
                {conditions.reportForm === reportSettlementList.结算周期报表 && conditions.compareType === compareTypeSelect.同比 && <div>
                    <Table
                        className="white-space-nowrap"
                        columns={columnsCycleYear}
                        dataSource={data}
                        rowKey="id"
                        pagination={false}
                        loading={loading || this.state.loading}
                        locale={locale}
                        {...TABLE}/>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>
                            {formatMessage({
                                id: 'tableCyclePanel.table.yearOnYear',
                                defaultMessage: '结算周期报表-同比'
                            })}</Col></Row>}>
                            <Chart forceFit data={dvRate}
                                style={{fontSize: '12'}}
                                height={400} scale={scale}
                                padding={['5%', '6%', '18%']}
                                onGetG2Instance={c => {
                                    this.chart = c;
                                }}>
                                <Legend
                                    custom
                                    allowAllCanceled
                                    items={legendItems}
                                    onClick={ev => this.onClickLegend(ev, legendItems, (formatMessage({
                                        id: 'tablePanel.column.changeRate',
                                        defaultMessage: '变化率'
                                    })))}/>
                                <Axis name="month" />
                                <Axis name="value" position={'left'} />
                                <Tooltip />
                                <Geom
                                    type="interval"
                                    position="month*value"
                                    color={['type', value => {
                                        if(value === `${year}${formatMessage({
                                            id: 'tablePanel.column.settlementCycle',
                                            defaultMessage: '结算周期'
                                        })}`)
                                            return '#F5B297';

                                        if(value === `${year - 1}${formatMessage({
                                            id: 'tablePanel.column.settlementCycle',
                                            defaultMessage: '结算周期'
                                        })}`)
                                            return '#A4C2E5';
                                    }]}
                                    adjust={[{
                                        type: 'dodge',
                                        marginRatio: 1 / 1.5,
                                    }]}>
                                    <Label
                                        content="value"
                                        textStyle={{
                                            textBaseline: 'top',
                                            fill: '#404040',
                                            fontSize: '12',
                                        }}/>

                                </Geom>
                                <View data={list} >
                                    <Geom type="line" position={`month*${`${formatMessage({
                                        id: 'tablePanel.column.changeRate',
                                        defaultMessage: '变化率'
                                    })}`}`} color="#A5A5A5" size={3} >
                                        <Label
                                            content={formatMessage({
                                                id: 'tablePanel.column.changeRate',
                                                defaultMessage: '变化率'
                                            })}
                                            textStyle={{
                                                textAlign: 'middle',
                                                fill: '#404040',
                                                fontSize: '12',
                                            }}/>
                                    </Geom>
                                    <Axis name={formatMessage({
                                        id: 'tablePanel.column.changeRate',
                                        defaultMessage: '变化率'
                                    })} position="right" />

                                </View>
                            </Chart>
                        </DescriptionList>
                    </Card>
                </div>}
                {conditions.compareType === compareTypeSelect.环比 && <div><Table
                    className="white-space-nowrap"
                    columns={columnsCycleLinkRatio}
                    dataSource={data}
                    rowKey="id"
                    pagination={false}
                    loading={loading || this.state.loading}
                    locale={locale}
                    {...TABLE}/>
                <Card>
                    <DescriptionList size="large" title={<Row><Col span={12}>
                        {formatMessage({
                            id: 'tableCyclePanel.table.linkRatio',
                            defaultMessage: '结算周期报表-环比'
                        })}</Col></Row>}>
                        <Chart height={400} data={contents} scale={cols} forceFit>
                            <Legend />
                            <Axis name="month" />
                            <Axis
                                name="value"
                                label={{
                                    formatter: val => `${val}`
                                }}/>
                            <Tooltip
                                crosshairs={{
                                    type: 'y'
                                }}/>
                            <Geom
                                type="line"
                                position="month*value"
                                size={2}
                                color={'year'}
                                shape={'smooth'}/>
                            <Geom
                                type="point"
                                position="month*value"
                                size={4}
                                shape={'circle'}
                                color={'year'}
                                style={{
                                    stroke: '#fff',
                                    lineWidth: 1
                                }}/>
                        </Chart>
                    </DescriptionList>

                </Card>
                </div>
                }
            </Card>
        );
    }
}

TableCyclePanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    intl: PropTypes.object,
};
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const mapStateToProps = state => ({
    data: getData(state),
    conditions: getConditions(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
});

import {connect} from 'react-redux';
import {injectIntl} from './intl';
export default connect(mapStateToProps, null)(injectIntl(TableCyclePanel));
